﻿using System;
using System.IO;
using System.Text;
using System.Threading;

namespace JinYuan.Helper
{
    public class TxtHelper
    {
        static ReaderWriterLockSlim sucessLogWriteLockSlim = new ReaderWriterLockSlim();

        /// <summary>
        /// 写入TEXT文本
        /// </summary>
        /// <param name="fullName">文件名</param>
        /// <param name="content">内容</param>
        /// <returns>保存结果</returns>
        public static bool WriteTxt(string fullName, string content)
        {
            FileStream fs = null;
            StreamWriter sw = null;

            try
            {
                string directory = fullName.Substring(0, fullName.LastIndexOf('\\'));
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                sucessLogWriteLockSlim.EnterWriteLock();//加锁防止抢占
                if (!File.Exists(fullName))
                {
                    fs = new FileStream(fullName, FileMode.Create, FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                }
                else
                {
                    fs = new FileStream(fullName, FileMode.Append, FileAccess.Write);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                }

                sw.WriteLine(content);

                sw.Close();
                fs.Close();

                return true;
            }
            catch (Exception ex)
            {
                sw?.Close();
                fs?.Close();

            }
            finally
            {
                sucessLogWriteLockSlim.ExitWriteLock();
            }

            return false;
        }

    }
}
